<template>
    <div class="business-register-container">
        <el-card shadow="hover">
            <div slot="header" class="clearfix">
                <h3 class="card-title">供应商注册</h3>
            </div>

            <el-form
                ref="registerForm"
                :model="form"
                :rules="rules"
                label-width="120px"
                label-position="top">

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="供应商名称" prop="name">
                            <el-input
                                v-model="form.name"
                                placeholder="请输入供应商名称"
                                clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="联系人姓名" prop="contact">
                            <el-input
                                v-model="form.contactName"
                                placeholder="请输入联系人姓名"
                                clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>


                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="联系电话" prop="contactPhone">
                            <el-input
                                v-model="form.contactPhone"
                                placeholder="请输入联系电话"
                                clearable>
                                <template slot="prepend">+86</template>
                            </el-input>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="供应商地址">
                            <el-cascader
                                :options="regionData"
                                v-model="form.address"
                                @blur="getRegion2">
                            </el-cascader>
                            <el-button type="default" @click="getRegion2">确定</el-button>
                            <el-input
                                class="address-detail"
                                v-model="form.addressDetail"
                                placeholder="请输入详细地址"
                                clearable>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item label="营业执照" prop="license">
                    <el-upload
                        class="license-uploader"
                        name="photo"
                        action="http://localhost:8888/product/upload"
                        :show-file-list="false"
                        :on-success="handleLicenseSuccess"
                        :before-upload="beforeLogoUpload">
                        <img v-if="form.license" :src="form.license" class="license-image">
                        <div v-else class="uploader-placeholder">
                            <i class="el-icon-plus"></i>
                            <div class="uploader-text">上传营业执照</div>
                        </div>
                    </el-upload>
                    <div class="upload-tip">请上传清晰的营业执照照片，支持JPG/PNG格式，大小不超过5MB</div>
                </el-form-item>

                <el-form-item label="供应商LOGO（选填）">
                    <el-upload
                        name="photo"
                        class="logo-uploader"
                        action="http://localhost:8888/product/upload"
                        :show-file-list="false"
                        :on-success="handleLogoSuccess"
                        :before-upload="beforeLogoUpload">
                        <img v-if="form.logo" :src="form.logo" class="logo-image">
                        <div v-else class="uploader-placeholder">
                            <i class="el-icon-plus"></i>
                            <div class="uploader-text">上传LOGO</div>
                        </div>
                    </el-upload>
                    <div class="upload-tip">建议尺寸200×200px，支持JPG/PNG格式</div>
                </el-form-item>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="注册日期" prop="createdAt">
                            <el-date-picker
                                v-model="form.createdAt"
                                type="datetime"
                                placeholder="选择注册日期"
                                style="width: 100%"
                                format="yyyy/MM/dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-form-item class="form-actions">
                    <el-button @click="handleCancel">返回</el-button>
                    <el-button
                        type="primary"
                        @click="submitForm"
                        :loading="submitting">
                        提交注册
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import { regionData, codeToText } from 'element-china-area-data';
import moment from "moment";
export default {
    name: "BusinessRegister",
    data() {
        //判断密码
        const validatePassword = (rule, value, callback) => {
            if (value !== this.form.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };

        return {
            submitting: false,
            form: {
                name: '',
                contactName: '',
                contactPhone: '',
                license: '',
                logo: '',
                address: [],
                addressDetail: '',
                createdAt: moment().format('YYYY-MM-DD HH:mm:ss')
            },
            // value1:'',
            rules: {
                name: [
                    { required: true, message: '请输入供应商名称', trigger: 'blur' },
                    { min: 2, max: 30, message: '长度在2到30个字符', trigger: 'blur' }
                ],
                contactName: [
                    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
                ],
                contactPhone: [
                    { required: true, message: '请输入联系电话', trigger: 'blur' },
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                ],
                license: [
                    { required: true, message: '请上传营业执照', trigger: 'change' }
                ],
                // address: [
                //     { type: 'array', required: true, message: '请选择省市区', trigger: 'change' }
                // ],
                addressDetail: [
                    { required: true, message: '请输入详细地址', trigger: 'blur' }
                ],
                createdAt: [
                    { required: true, message: '请选择注册日期', trigger: 'change' }
                ]
            },
            regionData,
        }
    },
    methods: {
        submitForm() {
            let user = JSON.parse(sessionStorage.getItem('user'))
            // let areaNames = this.form.address.map(code => codeToText[code])+this.form.addressDetail
            this.form.address = this.form.address.join(',')
            // this.form.addressDetail = areaNames
            this.$refs.registerForm.validate(valid => {
                if (valid) {
                    this.$axios.post(`suppliers/AddSupplier/${user.id}`,this.form).then(r => {
                        this.$message.success('申请成功');
                        this.resetForm();//重置表单
                    })
                } else {
                    this.$message.error('请填写完整的注册信息');
                    return false;
                }
            });
        },
        handleCancel() {
            this.$confirm('确定要放弃当前填写的内容吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$router.go(-1);
            }).catch(() => {
                this.$message.info('已取消');
            });
        },
        handleLicenseSuccess(res, file) {
            this.form.license = URL.createObjectURL(file.raw);
        },
        handleLogoSuccess(res, file) {
            this.form.logo = URL.createObjectURL(file.raw);
        },
        //图影片格式
        beforeLogoUpload(file) {
            const isImage = file.type === 'image/jpeg' || file.type === 'image/png';
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isImage) {
                this.$message.error('上传文件只能是JPG/PNG格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传文件大小不能超过2MB!');
            }
            return isImage && isLt2M;
        },

        getRegion2() {
            const areaNames = this.form.address.map(code => codeToText[code])
            console.log(9999, areaNames)
        },

// 新增重置表单方法
        resetForm() {
            this.form = {
                name: '',
                contactName: '',
                contactPhone: '',
                license: '',
                logo: '',
                address: [],
                addressDetail: '',
                createdAt: moment().format('YYYY-MM-DD HH:mm:ss')
            };
        }
    }
}
</script>

<style scoped>
.business-register-container {
    width: 800px;
    margin: 20px auto;
}

.card-title {
    margin: 0;
    color: #333;
    text-align: center;
}

.license-uploader, .logo-uploader {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 178px;
    height: 178px;
}

.license-uploader:hover, .logo-uploader:hover {
    border-color: #409EFF;
}

.license-image, .logo-image {
    width: 100%;
    height: 100%;
    display: block;
}

.uploader-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #8c939d;
}

.uploader-placeholder i {
    font-size: 28px;
    margin-bottom: 10px;
}

.uploader-text {
    font-size: 12px;
}

.upload-tip {
    font-size: 12px;
    color: #909399;
    margin-top: 8px;
}

.address-detail {
    margin-top: 10px;
}

.form-actions {
    text-align: center;
    margin-top: 30px;
}

.el-row {
    margin-bottom: 20px;
}
</style>